﻿using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
using DotNetty.Transport.Libuv;
using FileClient.Core.Configuration;
using Microsoft.Extensions.Options;

namespace FileClient.Core.Client;

public class DefaultBootstrapProvider : IBootstrapProvider
{
    private readonly FileServerOption _fileServerOption;
    private IEventLoopGroup group;
    public DefaultBootstrapProvider(IOptions<FileServerOption> fileServerOption)
    {
        _fileServerOption = fileServerOption.Value;
    }
    
    
    public Bootstrap CreateClientBootstrap()
    {
        
        var bootstrap = new Bootstrap();
        if (_fileServerOption.UseLibuv)
        {
            group = new EventLoopGroup();
        }
        else
        {
            group = new MultithreadEventLoopGroup();
        }

        bootstrap
            .Channel<TcpSocketChannel>()
            .Option(ChannelOption.ConnectTimeout, TimeSpan.FromMilliseconds(_fileServerOption.ConnectTimeout))
            .Group(group)
            ;
        return bootstrap;
    }
    
    public async void Dispose()
    {
        if (group != null)
        {
            await group.ShutdownGracefullyAsync();
        }
    }
}